Skip to main content

std/io/buffered/
bufreader.rs

1mod buffer;
2
3use buffer::Buffer;
4
5use crate::fmt;
6use crate::io::{
7    self, BorrowedCursor, BufRead, DEFAULT_BUF_SIZE, IoSliceMut, Read, Seek, SeekFrom, SizeHint,
8    SpecReadByte, uninlined_slow_read_byte,
9};
10
11/// The `BufReader<R>` struct adds buffering to any reader.
12///
13/// It can be excessively inefficient to work directly with a [`Read`] instance.
14/// For example, every call to [`read`][`TcpStream::read`] on [`TcpStream`]
15/// results in a system call. A `BufReader<R>` performs large, infrequent reads on
16/// the underlying [`Read`] and maintains an in-memory buffer of the results.
17///
18/// `BufReader<R>` can improve the speed of programs that make *small* and
19/// *repeated* read calls to the same file or network socket. It does not
20/// help when reading very large amounts at once, or reading just one or a few
21/// times. It also provides no advantage when reading from a source that is
22/// already in memory, like a <code>[Vec]\<u8></code>.
23///
24/// When the `BufReader<R>` is dropped, the contents of its buffer will be
25/// discarded. Creating multiple instances of a `BufReader<R>` on the same
26/// stream can cause data loss. Reading from the underlying reader after
27/// unwrapping the `BufReader<R>` with [`BufReader::into_inner`] can also cause
28/// data loss.
29///
30/// [`TcpStream::read`]: crate::net::TcpStream::read
31/// [`TcpStream`]: crate::net::TcpStream
32///
33/// # Examples
34///
35/// ```no_run
36/// use std::io::prelude::*;
37/// use std::io::BufReader;
38/// use std::fs::File;
39///
40/// fn main() -> std::io::Result<()> {
41///     let f = File::open("log.txt")?;
42///     let mut reader = BufReader::new(f);
43///
44///     let mut line = String::new();
45///     let len = reader.read_line(&mut line)?;
46///     println!("First line is {len} bytes long");
47///     Ok(())
48/// }
49/// ```
50#[stable(feature = "rust1", since = "1.0.0")]
51#[cfg_attr(not(test), rustc_diagnostic_item = "IoBufReader")]
52pub struct BufReader<R: ?Sized> {
53    buf: Buffer,
54    inner: R,
55}
56
57impl<R: Read> BufReader<R> {
58    /// Creates a new `BufReader<R>` with a default buffer capacity. The default is currently 8 KiB,
59    /// but may change in the future.
60    ///
61    /// # Examples
62    ///
63    /// ```no_run
64    /// use std::io::BufReader;
65    /// use std::fs::File;
66    ///
67    /// fn main() -> std::io::Result<()> {
68    ///     let f = File::open("log.txt")?;
69    ///     let reader = BufReader::new(f);
70    ///     Ok(())
71    /// }
72    /// ```
73    #[stable(feature = "rust1", since = "1.0.0")]
74    pub fn new(inner: R) -> BufReader<R> {
75        BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
76    }
77
78    pub(crate) fn try_new_buffer() -> io::Result<Buffer> {
79        Buffer::try_with_capacity(DEFAULT_BUF_SIZE)
80    }
81
82    pub(crate) fn with_buffer(inner: R, buf: Buffer) -> Self {
83        Self { inner, buf }
84    }
85
86    /// Creates a new `BufReader<R>` with the specified buffer capacity.
87    ///
88    /// # Examples
89    ///
90    /// Creating a buffer with ten bytes of capacity:
91    ///
92    /// ```no_run
93    /// use std::io::BufReader;
94    /// use std::fs::File;
95    ///
96    /// fn main() -> std::io::Result<()> {
97    ///     let f = File::open("log.txt")?;
98    ///     let reader = BufReader::with_capacity(10, f);
99    ///     Ok(())
100    /// }
101    /// ```
102    #[stable(feature = "rust1", since = "1.0.0")]
103    pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
104        BufReader { inner, buf: Buffer::with_capacity(capacity) }
105    }
106}
107
108impl<R: Read + ?Sized> BufReader<R> {
109    /// Attempt to look ahead `n` bytes.
110    ///
111    /// `n` must be less than or equal to `capacity`.
112    ///
113    /// The returned slice may be less than `n` bytes long if
114    /// end of file is reached.
115    ///
116    /// After calling this method, you may call [`consume`](BufRead::consume)
117    /// with a value less than or equal to `n` to advance over some or all of
118    /// the returned bytes.
119    ///
120    /// ## Examples
121    ///
122    /// ```rust
123    /// #![feature(bufreader_peek)]
124    /// use std::io::{Read, BufReader};
125    ///
126    /// let mut bytes = &b"oh, hello there"[..];
127    /// let mut rdr = BufReader::with_capacity(6, &mut bytes);
128    /// assert_eq!(rdr.peek(2).unwrap(), b"oh");
129    /// let mut buf = [0; 4];
130    /// rdr.read(&mut buf[..]).unwrap();
131    /// assert_eq!(&buf, b"oh, ");
132    /// assert_eq!(rdr.peek(5).unwrap(), b"hello");
133    /// let mut s = String::new();
134    /// rdr.read_to_string(&mut s).unwrap();
135    /// assert_eq!(&s, "hello there");
136    /// assert_eq!(rdr.peek(1).unwrap().len(), 0);
137    /// ```
138    #[unstable(feature = "bufreader_peek", issue = "128405")]
139    pub fn peek(&mut self, n: usize) -> io::Result<&[u8]> {
140        assert!(n <= self.capacity());
141        while n > self.buf.buffer().len() {
142            if self.buf.pos() > 0 {
143                self.buf.backshift();
144            }
145            let new = self.buf.read_more(&mut self.inner)?;
146            if new == 0 {
147                // end of file, no more bytes to read
148                return Ok(&self.buf.buffer()[..]);
149            }
150            debug_assert_eq!(self.buf.pos(), 0);
151        }
152        Ok(&self.buf.buffer()[..n])
153    }
154}
155
156impl<R: ?Sized> BufReader<R> {
157    /// Gets a reference to the underlying reader.
158    ///
159    /// It is inadvisable to directly read from the underlying reader.
160    ///
161    /// # Examples
162    ///
163    /// ```no_run
164    /// use std::io::BufReader;
165    /// use std::fs::File;
166    ///
167    /// fn main() -> std::io::Result<()> {
168    ///     let f1 = File::open("log.txt")?;
169    ///     let reader = BufReader::new(f1);
170    ///
171    ///     let f2 = reader.get_ref();
172    ///     Ok(())
173    /// }
174    /// ```
175    #[stable(feature = "rust1", since = "1.0.0")]
176    pub fn get_ref(&self) -> &R {
177        &self.inner
178    }
179
180    /// Gets a mutable reference to the underlying reader.
181    ///
182    /// It is inadvisable to directly read from the underlying reader.
183    ///
184    /// # Examples
185    ///
186    /// ```no_run
187    /// use std::io::BufReader;
188    /// use std::fs::File;
189    ///
190    /// fn main() -> std::io::Result<()> {
191    ///     let f1 = File::open("log.txt")?;
192    ///     let mut reader = BufReader::new(f1);
193    ///
194    ///     let f2 = reader.get_mut();
195    ///     Ok(())
196    /// }
197    /// ```
198    #[stable(feature = "rust1", since = "1.0.0")]
199    pub fn get_mut(&mut self) -> &mut R {
200        &mut self.inner
201    }
202
203    /// Returns a reference to the internally buffered data.
204    ///
205    /// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
206    ///
207    /// [`fill_buf`]: BufRead::fill_buf
208    ///
209    /// # Examples
210    ///
211    /// ```no_run
212    /// use std::io::{BufReader, BufRead};
213    /// use std::fs::File;
214    ///
215    /// fn main() -> std::io::Result<()> {
216    ///     let f = File::open("log.txt")?;
217    ///     let mut reader = BufReader::new(f);
218    ///     assert!(reader.buffer().is_empty());
219    ///
220    ///     if reader.fill_buf()?.len() > 0 {
221    ///         assert!(!reader.buffer().is_empty());
222    ///     }
223    ///     Ok(())
224    /// }
225    /// ```
226    #[stable(feature = "bufreader_buffer", since = "1.37.0")]
227    pub fn buffer(&self) -> &[u8] {
228        self.buf.buffer()
229    }
230
231    /// Returns the number of bytes the internal buffer can hold at once.
232    ///
233    /// # Examples
234    ///
235    /// ```no_run
236    /// use std::io::{BufReader, BufRead};
237    /// use std::fs::File;
238    ///
239    /// fn main() -> std::io::Result<()> {
240    ///     let f = File::open("log.txt")?;
241    ///     let mut reader = BufReader::new(f);
242    ///
243    ///     let capacity = reader.capacity();
244    ///     let buffer = reader.fill_buf()?;
245    ///     assert!(buffer.len() <= capacity);
246    ///     Ok(())
247    /// }
248    /// ```
249    #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
250    pub fn capacity(&self) -> usize {
251        self.buf.capacity()
252    }
253
254    /// Unwraps this `BufReader<R>`, returning the underlying reader.
255    ///
256    /// Note that any leftover data in the internal buffer is lost. Therefore,
257    /// a following read from the underlying reader may lead to data loss.
258    ///
259    /// # Examples
260    ///
261    /// ```no_run
262    /// use std::io::BufReader;
263    /// use std::fs::File;
264    ///
265    /// fn main() -> std::io::Result<()> {
266    ///     let f1 = File::open("log.txt")?;
267    ///     let reader = BufReader::new(f1);
268    ///
269    ///     let f2 = reader.into_inner();
270    ///     Ok(())
271    /// }
272    /// ```
273    #[stable(feature = "rust1", since = "1.0.0")]
274    pub fn into_inner(self) -> R
275    where
276        R: Sized,
277    {
278        self.inner
279    }
280
281    /// Invalidates all data in the internal buffer.
282    #[inline]
283    pub(in crate::io) fn discard_buffer(&mut self) {
284        self.buf.discard_buffer()
285    }
286}
287
288// This is only used by a test which asserts that the initialization-tracking is correct.
289#[cfg(test)]
290impl<R: ?Sized> BufReader<R> {
291    #[allow(missing_docs)]
292    pub fn initialized(&self) -> bool {
293        self.buf.initialized()
294    }
295}
296
297impl<R: ?Sized + Seek> BufReader<R> {
298    /// Seeks relative to the current position. If the new position lies within the buffer,
299    /// the buffer will not be flushed, allowing for more efficient seeks.
300    /// This method does not return the location of the underlying reader, so the caller
301    /// must track this information themselves if it is required.
302    #[stable(feature = "bufreader_seek_relative", since = "1.53.0")]
303    pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
304        let pos = self.buf.pos() as u64;
305        if offset < 0 {
306            if let Some(_) = pos.checked_sub((-offset) as u64) {
307                self.buf.unconsume((-offset) as usize);
308                return Ok(());
309            }
310        } else if let Some(new_pos) = pos.checked_add(offset as u64) {
311            if new_pos <= self.buf.filled() as u64 {
312                self.buf.consume(offset as usize);
313                return Ok(());
314            }
315        }
316
317        self.seek(SeekFrom::Current(offset)).map(drop)
318    }
319}
320
321impl<R> SpecReadByte for BufReader<R>
322where
323    Self: Read,
324{
325    #[inline]
326    fn spec_read_byte(&mut self) -> Option<io::Result<u8>> {
327        let mut byte = 0;
328        if self.buf.consume_with(1, |claimed| byte = claimed[0]) {
329            return Some(Ok(byte));
330        }
331
332        // Fallback case, only reached once per buffer refill.
333        uninlined_slow_read_byte(self)
334    }
335}
336
337#[stable(feature = "rust1", since = "1.0.0")]
338impl<R: ?Sized + Read> Read for BufReader<R> {
339    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
340        // If we don't have any buffered data and we're doing a massive read
341        // (larger than our internal buffer), bypass our internal buffer
342        // entirely.
343        if self.buf.pos() == self.buf.filled() && buf.len() >= self.capacity() {
344            self.discard_buffer();
345            return self.inner.read(buf);
346        }
347        let mut rem = self.fill_buf()?;
348        let nread = rem.read(buf)?;
349        self.consume(nread);
350        Ok(nread)
351    }
352
353    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
354        // If we don't have any buffered data and we're doing a massive read
355        // (larger than our internal buffer), bypass our internal buffer
356        // entirely.
357        if self.buf.pos() == self.buf.filled() && cursor.capacity() >= self.capacity() {
358            self.discard_buffer();
359            return self.inner.read_buf(cursor);
360        }
361
362        let prev = cursor.written();
363
364        let mut rem = self.fill_buf()?;
365        rem.read_buf(cursor.reborrow())?; // actually never fails
366
367        self.consume(cursor.written() - prev); //slice impl of read_buf known to never unfill buf
368
369        Ok(())
370    }
371
372    // Small read_exacts from a BufReader are extremely common when used with a deserializer.
373    // The default implementation calls read in a loop, which results in surprisingly poor code
374    // generation for the common path where the buffer has enough bytes to fill the passed-in
375    // buffer.
376    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
377        if self.buf.consume_with(buf.len(), |claimed| buf.copy_from_slice(claimed)) {
378            return Ok(());
379        }
380
381        crate::io::default_read_exact(self, buf)
382    }
383
384    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
385        if self.buf.consume_with(cursor.capacity(), |claimed| cursor.append(claimed)) {
386            return Ok(());
387        }
388
389        crate::io::default_read_buf_exact(self, cursor)
390    }
391
392    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
393        let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
394        if self.buf.pos() == self.buf.filled() && total_len >= self.capacity() {
395            self.discard_buffer();
396            return self.inner.read_vectored(bufs);
397        }
398        let mut rem = self.fill_buf()?;
399        let nread = rem.read_vectored(bufs)?;
400
401        self.consume(nread);
402        Ok(nread)
403    }
404
405    fn is_read_vectored(&self) -> bool {
406        self.inner.is_read_vectored()
407    }
408
409    // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
410    // delegate to the inner implementation.
411    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
412        let inner_buf = self.buffer();
413        buf.try_reserve(inner_buf.len())?;
414        buf.extend_from_slice(inner_buf);
415        let nread = inner_buf.len();
416        self.discard_buffer();
417        Ok(nread + self.inner.read_to_end(buf)?)
418    }
419
420    // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
421    // delegate to the inner implementation.
422    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
423        // In the general `else` case below we must read bytes into a side buffer, check
424        // that they are valid UTF-8, and then append them to `buf`. This requires a
425        // potentially large memcpy.
426        //
427        // If `buf` is empty--the most common case--we can leverage `append_to_string`
428        // to read directly into `buf`'s internal byte buffer, saving an allocation and
429        // a memcpy.
430        if buf.is_empty() {
431            // `append_to_string`'s safety relies on the buffer only being appended to since
432            // it only checks the UTF-8 validity of new data. If there were existing content in
433            // `buf` then an untrustworthy reader (i.e. `self.inner`) could not only append
434            // bytes but also modify existing bytes and render them invalid. On the other hand,
435            // if `buf` is empty then by definition any writes must be appends and
436            // `append_to_string` will validate all of the new bytes.
437            unsafe { crate::io::append_to_string(buf, |b| self.read_to_end(b)) }
438        } else {
439            // We cannot append our byte buffer directly onto the `buf` String as there could
440            // be an incomplete UTF-8 sequence that has only been partially read. We must read
441            // everything into a side buffer first and then call `from_utf8` on the complete
442            // buffer.
443            let mut bytes = Vec::new();
444            self.read_to_end(&mut bytes)?;
445            let string = crate::str::from_utf8(&bytes).map_err(|_| io::Error::INVALID_UTF8)?;
446            *buf += string;
447            Ok(string.len())
448        }
449    }
450}
451
452#[stable(feature = "rust1", since = "1.0.0")]
453impl<R: ?Sized + Read> BufRead for BufReader<R> {
454    fn fill_buf(&mut self) -> io::Result<&[u8]> {
455        self.buf.fill_buf(&mut self.inner)
456    }
457
458    fn consume(&mut self, amt: usize) {
459        self.buf.consume(amt)
460    }
461}
462
463#[stable(feature = "rust1", since = "1.0.0")]
464impl<R> fmt::Debug for BufReader<R>
465where
466    R: ?Sized + fmt::Debug,
467{
468    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
469        fmt.debug_struct("BufReader")
470            .field("reader", &&self.inner)
471            .field(
472                "buffer",
473                &format_args!("{}/{}", self.buf.filled() - self.buf.pos(), self.capacity()),
474            )
475            .finish()
476    }
477}
478
479#[stable(feature = "rust1", since = "1.0.0")]
480impl<R: ?Sized + Seek> Seek for BufReader<R> {
481    /// Seek to an offset, in bytes, in the underlying reader.
482    ///
483    /// The position used for seeking with <code>[SeekFrom::Current]\(_)</code> is the
484    /// position the underlying reader would be at if the `BufReader<R>` had no
485    /// internal buffer.
486    ///
487    /// Seeking always discards the internal buffer, even if the seek position
488    /// would otherwise fall within it. This guarantees that calling
489    /// [`BufReader::into_inner()`] immediately after a seek yields the underlying reader
490    /// at the same position.
491    ///
492    /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
493    ///
494    /// See [`std::io::Seek`] for more details.
495    ///
496    /// Note: In the edge case where you're seeking with <code>[SeekFrom::Current]\(n)</code>
497    /// where `n` minus the internal buffer length overflows an `i64`, two
498    /// seeks will be performed instead of one. If the second seek returns
499    /// [`Err`], the underlying reader will be left at the same position it would
500    /// have if you called `seek` with <code>[SeekFrom::Current]\(0)</code>.
501    ///
502    /// [`std::io::Seek`]: Seek
503    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
504        let result: u64;
505        if let SeekFrom::Current(n) = pos {
506            let remainder = (self.buf.filled() - self.buf.pos()) as i64;
507            // it should be safe to assume that remainder fits within an i64 as the alternative
508            // means we managed to allocate 8 exbibytes and that's absurd.
509            // But it's not out of the realm of possibility for some weird underlying reader to
510            // support seeking by i64::MIN so we need to handle underflow when subtracting
511            // remainder.
512            if let Some(offset) = n.checked_sub(remainder) {
513                result = self.inner.seek(SeekFrom::Current(offset))?;
514            } else {
515                // seek backwards by our remainder, and then by the offset
516                self.inner.seek(SeekFrom::Current(-remainder))?;
517                self.discard_buffer();
518                result = self.inner.seek(SeekFrom::Current(n))?;
519            }
520        } else {
521            // Seeking with Start/End doesn't care about our buffer length.
522            result = self.inner.seek(pos)?;
523        }
524        self.discard_buffer();
525        Ok(result)
526    }
527
528    /// Returns the current seek position from the start of the stream.
529    ///
530    /// The value returned is equivalent to `self.seek(SeekFrom::Current(0))`
531    /// but does not flush the internal buffer. Due to this optimization the
532    /// function does not guarantee that calling `.into_inner()` immediately
533    /// afterwards will yield the underlying reader at the same position. Use
534    /// [`BufReader::seek`] instead if you require that guarantee.
535    ///
536    /// # Panics
537    ///
538    /// This function will panic if the position of the inner reader is smaller
539    /// than the amount of buffered data. That can happen if the inner reader
540    /// has an incorrect implementation of [`Seek::stream_position`], or if the
541    /// position has gone out of sync due to calling [`Seek::seek`] directly on
542    /// the underlying reader.
543    ///
544    /// # Example
545    ///
546    /// ```no_run
547    /// use std::{
548    ///     io::{self, BufRead, BufReader, Seek},
549    ///     fs::File,
550    /// };
551    ///
552    /// fn main() -> io::Result<()> {
553    ///     let mut f = BufReader::new(File::open("foo.txt")?);
554    ///
555    ///     let before = f.stream_position()?;
556    ///     f.read_line(&mut String::new())?;
557    ///     let after = f.stream_position()?;
558    ///
559    ///     println!("The first line was {} bytes long", after - before);
560    ///     Ok(())
561    /// }
562    /// ```
563    fn stream_position(&mut self) -> io::Result<u64> {
564        let remainder = (self.buf.filled() - self.buf.pos()) as u64;
565        self.inner.stream_position().map(|pos| {
566            pos.checked_sub(remainder).expect(
567                "overflow when subtracting remaining buffer size from inner stream position",
568            )
569        })
570    }
571
572    /// Seeks relative to the current position.
573    ///
574    /// If the new position lies within the buffer, the buffer will not be
575    /// flushed, allowing for more efficient seeks. This method does not return
576    /// the location of the underlying reader, so the caller must track this
577    /// information themselves if it is required.
578    fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
579        self.seek_relative(offset)
580    }
581}
582
583impl<T: ?Sized> SizeHint for BufReader<T> {
584    #[inline]
585    fn lower_bound(&self) -> usize {
586        SizeHint::lower_bound(self.get_ref()) + self.buffer().len()
587    }
588
589    #[inline]
590    fn upper_bound(&self) -> Option<usize> {
591        SizeHint::upper_bound(self.get_ref()).and_then(|up| self.buffer().len().checked_add(up))
592    }
593}